package com.imooc.mall.service.impl;

import com.imooc.mall.exception.ImoocMallException;
import com.imooc.mall.exception.ImoocMallExceptionEnum;
import com.imooc.mall.model.dao.UserMapper;
import com.imooc.mall.model.pojo.User;
import com.imooc.mall.service.UserService;
import com.imooc.mall.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public User getUser() {
        return userMapper.selectByPrimaryKey(1);
    }

    @Override
    public void register(String username, String password) throws ImoocMallException {
        //判断该名字是否存在
        User user = userMapper.insertByName(username);
        if (user != null){
            throw new ImoocMallException(ImoocMallExceptionEnum.NAME_EXISTED);
        }
        //将该数据添加到数据库
        User user1 = new User();
        user1.setUsername(username);
       //此方法太过简单，需要通过md5 进行加密 user1.setPassword(password);
        try {
            user1.setPassword(MD5Utils.getMD5(password));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        int i = userMapper.insertSelective(user1);
        if (i==0){
            throw new ImoocMallException(ImoocMallExceptionEnum.INSERT_FAILED);
        }
    }



    @Override
    public User login(String username, String password) {

        String MD5Password=null;
        //先对当前密码进行加密
        try {
            MD5Password=MD5Utils.getMD5(password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        //进行登录检查
        User user = userMapper.insertLogin(username, MD5Password);
        if (user==null){
            throw new ImoocMallException(ImoocMallExceptionEnum.PASSWORD_OR_NAME_FAILED);
        }

        return user;
    }

    /**
     * 修改用户签名
     */
    @Override
    public void updateSignature(User user){
        int i = userMapper.updateByPrimaryKeySelective(user);
        if (i>1){
            throw new ImoocMallException(ImoocMallExceptionEnum.UPDATE_FAILED);
        }
    }

    /**
     * 判断该用户是否是管理员
     */
    @Override
    public Boolean checkAdminRole(User user){
        return user.getRole().equals(2);
    }
}
